package com.sakura.demo.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.sakura.demo.common.constant.AuthConstant;
import com.sakura.demo.gateway.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @Author: zhengcan
 * @Date: 2022/5/13
 * @Description: 将登录用户的JWT转化成用户信息的全局过滤器
 * @Version: 1.0.0 创建
 */
@Component
@Slf4j
public class UserInfoFromJwtGlobalFilter implements WebFilter{

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String toekn = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StrUtil.isEmptyIfStr(toekn)) {
            return chain.filter(exchange);
        }
        String userStr = JwtTokenUtil.parseTokenToJsonStr(toekn);
        log.info("[UserInfoFromJwtGlobalFilter]: 用户信息={}", userStr);
        ServerHttpRequest newRequest = exchange.getRequest().mutate()
                .header(AuthConstant.USER_INFO_HEADER, userStr).build();
        return chain.filter(exchange.mutate().request(newRequest).build());
    }
}
